<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// 检查用户是否已登录，且是医生角色
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'doctor') {
    header("Location: ../login.php");
    exit();
}

// 检查是否提供了病历ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_msg'] = "未提供有效的病历ID";
    header("Location: records.php");
    exit();
}

$record_id = $_GET['id'];
$doctor_id = $_SESSION['user_id'];

// 获取医生信息
$stmt = $conn->prepare("SELECT * FROM users u JOIN doctors d ON u.id = d.user_id WHERE u.id = ?");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$doctor_info = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 获取病历详情，确保只能查看自己创建的病历
$stmt = $conn->prepare("
    SELECT mr.*, 
           p.name as patient_name, p.gender, p.birthday, p.phone, p.id_card, p.address, p.medical_history, p.allergy,
           a.symptoms as appointment_symptoms
    FROM medical_records mr 
    JOIN patients p ON mr.patient_id = p.id 
    LEFT JOIN appointments a ON mr.appointment_id = a.id
    WHERE mr.id = ? AND mr.doctor_id = ?
");
$stmt->bind_param("ii", $record_id, $doctor_info['id']);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_msg'] = "病历不存在或您无权查看";
    header("Location: records.php");
    exit();
}

$record = $result->fetch_assoc();
$stmt->close();

// 获取处方药品信息
$stmt = $conn->prepare("
    SELECT pm.*, m.name as medicine_name, m.specification, m.manufacturer, m.category, m.unit, m.price
    FROM prescription_medicines pm 
    JOIN medicines m ON pm.medicine_id = m.id
    WHERE pm.medical_record_id = ?
    ORDER BY pm.id
");
$stmt->bind_param("i", $record_id);
$stmt->execute();
$prescriptions = $stmt->get_result();
$stmt->close();

// 计算患者年龄
$birthday = new DateTime($record['birthday']);
$today = new DateTime();
$age = $birthday->diff($today)->y;
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>病历详情 - 医生工作站</title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
    <link rel="stylesheet" href="/assets\css/all_de197510.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="../assets/images/hospital-logo.png" alt="医院标志" class="img-fluid rounded-circle mx-auto d-block" style="width: 80px;">
                        <h5 class="text-white mt-2"><?php echo htmlspecialchars($doctor_info['name']); ?></h5>
                        <p class="text-muted"><?php echo htmlspecialchars($doctor_info['department_name']); ?></p>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="index.php">
                                <i class="fas fa-home"></i> 工作台首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> 预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="patients.php">
                                <i class="fas fa-user-injured"></i> 患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active text-white" href="records.php">
                                <i class="fas fa-notes-medical"></i> 病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="prescriptions.php">
                                <i class="fas fa-prescription"></i> 处方管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="schedule.php">
                                <i class="fas fa-clock"></i> 排班管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="profile.php">
                                <i class="fas fa-user-md"></i> 个人信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="../logout.php">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">病历详情</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="records.php" class="btn btn-sm btn-outline-secondary me-2">
                            <i class="fas fa-arrow-left"></i> 返回列表
                        </a>
                        <a href="edit_record.php?id=<?php echo $record_id; ?>" class="btn btn-sm btn-outline-primary me-2">
                            <i class="fas fa-edit"></i> 编辑病历
                        </a>
                        <a href="print_record.php?id=<?php echo $record_id; ?>" class="btn btn-sm btn-outline-secondary" target="_blank">
                            <i class="fas fa-print"></i> 打印病历
                        </a>
                    </div>
                </div>

                <!-- 病历详情 -->
                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card border-primary">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">患者基本信息</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label fw-bold">姓名</label>
                                        <p><?php echo htmlspecialchars($record['patient_name']); ?></p>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label fw-bold">性别</label>
                                        <p><?php echo htmlspecialchars($record['gender']); ?></p>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label fw-bold">年龄</label>
                                        <p><?php echo $age; ?>岁</p>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label fw-bold">出生日期</label>
                                        <p><?php echo htmlspecialchars($record['birthday']); ?></p>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label fw-bold">身份证号</label>
                                        <p><?php echo htmlspecialchars($record['id_card']); ?></p>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label fw-bold">联系电话</label>
                                        <p><?php echo htmlspecialchars($record['phone']); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label fw-bold">地址</label>
                                        <p><?php echo htmlspecialchars($record['address']); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card h-100">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">既往病史</h5>
                            </div>
                            <div class="card-body">
                                <p><?php echo nl2br(htmlspecialchars($record['medical_history'] ?: '无')); ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card h-100">
                            <div class="card-header bg-warning text-dark">
                                <h5 class="mb-0">过敏史</h5>
                            </div>
                            <div class="card-body">
                                <p><?php echo nl2br(htmlspecialchars($record['allergy'] ?: '无')); ?></p>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (!empty($record['appointment_symptoms'])): ?>
                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header bg-secondary text-white">
                                <h5 class="mb-0">预约症状描述</h5>
                            </div>
                            <div class="card-body">
                                <p><?php echo nl2br(htmlspecialchars($record['appointment_symptoms'])); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">诊断信息</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label fw-bold">主诉</label>
                                        <p><?php echo nl2br(htmlspecialchars($record['main_complaint'])); ?></p>
                                    </div>
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label fw-bold">现病史</label>
                                        <p><?php echo nl2br(htmlspecialchars($record['present_illness'])); ?></p>
                                    </div>
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label fw-bold">诊断结果</label>
                                        <p><?php echo nl2br(htmlspecialchars($record['diagnosis'])); ?></p>
                                    </div>
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label fw-bold">治疗方案</label>
                                        <p><?php echo nl2br(htmlspecialchars($record['treatment'])); ?></p>
                                    </div>
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label fw-bold">医嘱</label>
                                        <p><?php echo nl2br(htmlspecialchars($record['notes'])); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($prescriptions->num_rows > 0): ?>
                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header bg-danger text-white">
                                <h5 class="mb-0">处方药品</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover">
                                        <thead class="table-light">
                                            <tr>
                                                <th>药品名称</th>
                                                <th>规格</th>
                                                <th>用法用量</th>
                                                <th>频次</th>
                                                <th>天数</th>
                                                <th>数量</th>
                                                <th>单价</th>
                                                <th>小计</th>
                                                <th>备注</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $total_price = 0;
                                            while ($prescription = $prescriptions->fetch_assoc()): 
                                                $subtotal = $prescription['price'] * $prescription['quantity'];
                                                $total_price += $subtotal;
                                            ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($prescription['medicine_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($prescription['specification']); ?></td>
                                                    <td><?php echo htmlspecialchars($prescription['dosage']); ?></td>
                                                    <td><?php echo htmlspecialchars($prescription['frequency']); ?></td>
                                                    <td><?php echo htmlspecialchars($prescription['days']); ?></td>
                                                    <td><?php echo htmlspecialchars($prescription['quantity'] . ' ' . $prescription['unit']); ?></td>
                                                    <td><?php echo number_format($prescription['price'], 2); ?></td>
                                                    <td><?php echo number_format($subtotal, 2); ?></td>
                                                    <td><?php echo htmlspecialchars($prescription['notes']); ?></td>
                                                </tr>
                                            <?php endwhile; ?>
                                            <tr class="table-secondary">
                                                <td colspan="7" class="text-end fw-bold">总计：</td>
                                                <td colspan="2" class="fw-bold"><?php echo number_format($total_price, 2); ?> 元</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <p><strong>录入医生：</strong> <?php echo htmlspecialchars($doctor_info['name']); ?></p>
                                    </div>
                                    <div class="col-md-6 text-end">
                                        <p><strong>创建时间：</strong> <?php echo date('Y-m-d H:i:s', strtotime($record['created_at'])); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="/assets\js/jquery-3.6.0.min.js"></script></script></script>
    <script src="/assets\js/bootstrap.bundle.min.js"></script></script></script>
</body>
</html> 